package com.element.security.resource.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.common.core.exception.ExceptionFactory;
import com.element.security.model.entity.AuthUserE;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @auther WuJun.Zhang
 * @date 2022/2/22 下午5:08
 */
public class SecurityContext {

    private static final TransmittableThreadLocal<AuthUserE> localUser = new TransmittableThreadLocal<>();
    private static final TransmittableThreadLocal<String> localContextAppId = new TransmittableThreadLocal<>();

    public static AuthUserE getUser() {
        AuthUserE authUser = localUser.get();
        if (null == authUser) {
            throw ExceptionFactory.bizException("用户不存在");
        }
        return authUser;
    }

    // 根据拓展KEY获取拓展值
    public static <T> T getExpValue(String key) {
        AuthUserE authUser = getUser();
        Map<String, Object> expMap = authUser.getExpMap();
        if (CollectionUtils.isEmpty(expMap)) {
            throw ExceptionFactory.bizException("拓展字段为空");
        }
        Object value = expMap.get(key);
        if (null == value) {
            throw ExceptionFactory.bizException("拓展值不存在");
        }
        return (T) value;
    }


    public static String getAppId() {
        return localContextAppId.get();
    }

    public static void putUser(AuthUserE user) {
        if (null == user) {
            return;
        }
        localUser.set(user);
    }

    public static void removeUser() {
        localUser.remove();
    }

    public static void putAppId(String appId) {
        if (StringUtils.isEmpty(appId)) {
            return;
        }
        localContextAppId.set(appId);
    }

    public static void removeAppId() {
        localContextAppId.remove();
    }

}